package org.mayuanxiaonong.timserver.config;

import java.io.File;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.mayuanxiaonong.timserver.util.ConfigException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 系统参数配置文件加载类
 * 
 * @author 9527
 *
 */
public class Config {

	private static final Logger log = LoggerFactory.getLogger(Config.class);

	private static final String DEFAULT_SERVER_HOST = "127.0.0.1";
	private static final int DEFAULT_SERVER_PORT = 9000;

	private static final int DEFAULT_HEART_BEAT_IDLE = 5;
	private static final int DEFAULT_HEART_BEAT_RETRY = 3;

	private static Config instance = new Config();

	private String serverHost = DEFAULT_SERVER_HOST;
	private int serverPort = DEFAULT_SERVER_PORT;

	private int heartBeatIdle = DEFAULT_HEART_BEAT_IDLE;
	private int heartBeatRetry = DEFAULT_HEART_BEAT_RETRY;

	public static Config getInstance() {
		return instance;
	}

	private Config() {
		loadConfig();
	}

	private void loadConfig() {
		File configFile = new File(SystemConfig.getInstance().getConfDir(),
				"config.xml");
		if (!configFile.exists()) {
			throw new ConfigException("Config file "
					+ configFile.getAbsolutePath() + " not found");
		}

		try {
			Configuration config = new XMLConfiguration(configFile);

			serverHost = config.getString("server.host", DEFAULT_SERVER_HOST);
			serverPort = config.getInt("server.port", DEFAULT_SERVER_PORT);

			heartBeatIdle = config.getInt("heartbeat.idle",
					DEFAULT_HEART_BEAT_IDLE);
			heartBeatRetry = config.getInt("heartbeat.retry",
					DEFAULT_HEART_BEAT_RETRY);

		} catch (ConfigurationException e) {
			log.error("加载配置文件失败," + configFile, e);
		}
	}

	public String getServerHost() {
		return serverHost;
	}

	public int getServerPort() {
		return serverPort;
	}

	public int getHeartBeatIdle() {
		return heartBeatIdle;
	}

	public int getHeartBeatRetry() {
		return heartBeatRetry;
	}

}
